import asyncio

from django.db import transaction

from llm.entity.metadatas import VectorStoreMetadata, AssistantMetadata
from llm.models import Users
from llm.service.AssistantService import AssistantService
from llm.service.OpenAIService import (OpenAIThreadService, OpenAIVectorStoreService)
from llm.service.ThreadService import ThreadService
from llm.service.VectorStoreService import VectorStoreService
from users.entity.serializers import RegisterSerializer


class UserService:
    @classmethod
    @transaction.atomic
    def init_user(cls, serializer: RegisterSerializer):
        """
        初始化用户，为其分配默认的智慧家庭的助手和thread
        :return:
        """
        # TODO:这里的事务管理有点问题，需要优化
        user: Users = serializer.save()

        # 创建默认的智慧家庭助手
        # TODO：这里的逻辑后续需要优化，目前先用一个默认的助手（OneNET）,用作指令解析
        assistant = AssistantService.create_for_parser(
            user=user,
            assistant_name='init_OneNET设备指令解析助手',
            metadata=AssistantMetadata(
                user_id=user.user_id,
                isInit='True',
                usage='智能家居助手',
                type='0'
            ),
        )
        # TODO:为新建的助手附加vector store,暂时不写metadata，且没配置文件，后续需要优化
        VectorStoreService.create(
            vector_name='全家助手VectorStore',
            assistant_id=assistant.id,
            user=user,
            metadata=VectorStoreMetadata(user_id=user.user_id, isInit='True')
        )
        thread = ThreadService.create(user_id=user.user_id)
        print(f'init user success, user_id:{user.user_id}')
        print(f"assistant_id:{assistant.id}, thread_id:{thread.id},vector_store_id:{assistant.id}")